<?php

namespace app\home\controller;

use app\admin\model\QuanGuanMemberModel;
use app\utils\Response;
use think\Controller;
use think\facade\Request;

class ApiBase extends Controller
{

    /*
     * ERROR_CODE
     * 系统参数
     * 200 成功
     * 401 token异常，需要登录
     * 500 发生错误
     * */

    // 不需要验证权限的接口
    protected $whiteList = [
        "MemberController/register", // 注册
        "MemberController/login", // 登录
        "CityController/getProvinceList", // 获取省列表
        "CityController/getChild", // 获取城市/区域列表
        "CheckInController/initCheckDate", // 初始化签到表数据
        "SystemController/info", // 系统信息
//        "MemberController/team", // 测试，后面需要删除
    ];

    // 请求参数
    protected $requestData = [];

    // app的版本号，用于后面做版本兼容
    protected $osVersion;

    // app类型，用于后面做版本兼容
    protected $osType;

    // 当前登录的用户信息
    protected $memberInfo = [];

    public function initialize()
    {

        $route = $this->request->routeInfo()['route'];
        // 当前请求的方式
        $method = $this->request->method();
        // 用户的TOKEN
        $authToken = $this->request->header('authToken');
        $contentType = $this->request->contentType();
        if ($method == "POST" && $route != "FileController/upload") {
            if ($contentType != "application/json") {
                Response::fail("the contentType must is application/json");
            }
        }
        $this->requestData = $this->request->param();

        // 记录请求日志
        writeRequestLog($route);
        writeRequestLog($this->requestData);

        // 是否需要登录权限
        if (!in_array($route, $this->whiteList) && !$this->checkToken($authToken)) {
            Response::fail('未登录或登录超时~', 401);
        }

    }


    /**
     * 检查token是否有效
     * @param $authToken
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function checkToken($authToken)
    {
        $memberModel = new QuanGuanMemberModel();
        $memberInfo = $memberModel->where([
            'token' => $authToken
        ])->find();
        if (empty($memberInfo)) {
            return false;
        }
        if ($memberInfo->status == 2 || $memberInfo->is_delete == 2) {
            Response::fail('账号已经被禁用');
        }
        if ($memberInfo->token_expire_time <= time()) {
            return false;
        }
        $this->memberInfo = $memberInfo;
        return true;
    }
}
